<template>
  <div class="login-record-container">
    
    <div class="login-record-content">
      <el-card class="login-record-card">
        <template #header>
          <div class="card-header">
            <el-icon><View /></el-icon>
            <span>登录记录列表</span>
          </div>
        </template>
        
        <div class="search-bar">
          <el-input 
            v-model="searchKey" 
            placeholder="请输入搜索关键词（用户名、IP、位置）"
            prefix-icon="Search"
            style="width: 300px;"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
        
        <el-table 
          v-loading="loading" 
          :data="loginRecords" 
          style="width: 100%"
          border
          stripe
          :empty-text="'暂无登录记录数据'"
          :row-style="(row) => row.loginStatus === 1 ? { backgroundColor: '#fff1f0' } : {}"
          :header-cell-style="{ backgroundColor: '#fafafa', fontWeight: 'bold' }"
        >
          <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip>
            <template #default="scope">
              <span style="font-weight: bold;">{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="loginStatus" label="登录状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.loginStatus === 0 ? 'success' : 'danger'">
                {{ scope.row.loginStatus === 0 ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="loginTime" label="登录时间" width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="time-icon"><Clock /></el-icon>
                {{ formatDateTime(scope.row.loginTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="loginIp" label="登录IP" width="140">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="ip-icon"><Iphone /></el-icon>
                {{ scope.row.loginIp }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastRefreshTime" label="最后刷新时间" width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="refresh-icon"><RefreshRight /></el-icon>
                {{ scope.row.lastRefreshTime ? formatDateTime(scope.row.lastRefreshTime) : '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tokenRefreshCount" label="Token刷新次数" width="180">
            <template #default="scope">
              <div class="refresh-count-display">
                <el-tag :type="getRefreshCountType(scope.row.tokenRefreshCount)">
                  {{ scope.row.tokenRefreshCount }}
                </el-tag>
                <div class="progress-container">
                  <el-progress 
                    :percentage="Math.min(scope.row.tokenRefreshCount * 10, 100)" 
                    :color="getRefreshCountColor(scope.row.tokenRefreshCount)"
                    :stroke-width="6"
                    :show-text="false"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="logoutTime" label="登出时间" width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="logout-icon"><SwitchButton /></el-icon>
                {{ scope.row.logoutTime ? formatDateTime(scope.row.logoutTime) : '未登出' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="loginLocation" label="登录位置" min-width="150" show-overflow-tooltip>            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="location-icon"><MapLocation /></el-icon>
                {{ scope.row.loginLocation || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="browser" label="浏览器" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="browser-icon"><Monitor /></el-icon>
                {{ scope.row.browser || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="os" label="操作系统" width="140">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="os-icon"><Monitor /></el-icon>
                {{ scope.row.os || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="deviceInfo" label="设备信息" min-width="140" show-overflow-tooltip>
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="device-icon"><Phone /></el-icon>
                {{ scope.row.deviceInfo || '-' }}
              </div>
            </template>
          </el-table-column>
      
          <el-table-column prop="accessToken" label="访问令牌" min-width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-tooltip :content="scope.row.accessToken || '-'" placement="top" effect="dark" :show-after="500">
                  <span>{{ maskToken(scope.row.accessToken) }}</span>
                </el-tooltip>
                <el-tooltip content="复制令牌" placement="top">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="handleCopyToken(scope.row.accessToken)"
                    icon="CopyDocument"
                    circle
                  />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="accessTokenExpire" label="令牌过期时间" width="180">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="expire-icon"><Timer /></el-icon>
                <span :style="getExpireTimeStyle(scope.row.accessTokenExpire)">
                  {{ scope.row.accessTokenExpire ? formatDateTime(scope.row.accessTokenExpire) : '-' }}
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="comment" label="描述信息" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="comment-icon"><ChatDotRound /></el-icon>
                {{ scope.row.comment || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="errorMessage" label="错误信息" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-icon class="error-icon"><WarningFilled /></el-icon>
                {{ scope.row.errorMessage || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdTime) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { View, Search, Clock, Iphone, RefreshRight, SwitchButton, CopyDocument, Timer, ChatDotRound, WarningFilled, MapLocation, Monitor, Phone } from '@element-plus/icons-vue'
import notificationService from '../utils/notificationService.js'
import { getLoginRecords } from '../api/auth.js'

export default {
  name: 'LoginRecord',
  components: {
    View,
    Search,
    Clock,
    Iphone,
    RefreshRight,
    SwitchButton,
    CopyDocument,
    Timer,
    ChatDotRound,
    WarningFilled,
    MapLocation,
    Monitor,
    Phone
  },
  setup() {
    const loading = ref(false)
    const loginRecords = ref([])
    const searchKey = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return dateString
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        console.warn('日期格式化错误:', error)
        return dateString
      }
    }
    
    // 掩码处理访问令牌，只显示前10位和后10位
    const maskToken = (token) => {
      if (!token || typeof token !== 'string') return '-'
      if (token.length <= 20) return token
      return `${token.substring(0, 10)}...${token.substring(token.length - 10)}`
    }
    
    // 根据刷新次数获取标签类型
    const getRefreshCountType = (count) => {
      if (!count || count === 0) return 'default'
      if (count <= 5) return 'primary'
      if (count <= 10) return 'success'
      if (count <= 20) return 'warning'
      return 'danger'
    }
    
    // 根据刷新次数获取进度条颜色
    const getRefreshCountColor = (count) => {
      if (!count || count === 0) return '#dcdfe6'
      if (count <= 5) return '#409eff'
      if (count <= 10) return '#67c23a'
      if (count <= 20) return '#e6a23c'
      return '#f56c6c'
    }
    
    // 处理复制令牌功能
    const handleCopyToken = (token) => {
      if (!token) return
      navigator.clipboard.writeText(token).then(() => {
        notificationService.success('令牌已复制到剪贴板')
      }).catch(() => {
        notificationService.error('复制失败，请手动复制')
      })
    }
    
    // 根据过期时间计算样式
    const getExpireTimeStyle = (expireTime) => {
      if (!expireTime) return {}
      
      try {
        const now = new Date()
        const expire = new Date(expireTime)
        const hoursDiff = (expire - now) / (1000 * 60 * 60)
        
        // 已过期
        if (hoursDiff <= 0) {
          return { color: '#f56c6c', fontWeight: 'bold' }
        }
        // 24小时内过期 - 警告
        else if (hoursDiff <= 24) {
          return { color: '#e6a23c' }
        }
        // 7天内过期 - 提示
        else if (hoursDiff <= 24 * 7) {
          return { color: '#67c23a' }
        }
      } catch (error) {
        console.warn('计算过期时间样式错误:', error)
      }
      
      return {}
    }
    
    // 加载登录记录
    const loadLoginRecords = async () => {
      loading.value = true
      try {
        const response = await getLoginRecords({
          searchKey: searchKey.value,
          pageSize: pageSize.value,
          currentPage: currentPage.value
        })
        
        // 检查响应是否成功
        if ((response.code >= 20000 && response.code <= 20003) && response.data) {
          loginRecords.value = response.data.records || []
          total.value = response.data.total || 0
        } else {
          notificationService.error(response.message || '获取登录记录失败')
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || error.message || '获取登录记录失败'
        notificationService.error(errorMessage)
        console.error('获取登录记录失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadLoginRecords()
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchKey.value = ''
      currentPage.value = 1
      loadLoginRecords()
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadLoginRecords()
    }
    
    // 当前页变化
    const handleCurrentChange = (current) => {
      currentPage.value = current
      loadLoginRecords()
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadLoginRecords()
    })
    
    return {
      loading,
      loginRecords,
      searchKey,
      currentPage,
      pageSize,
      total,
      formatDateTime,
      maskToken,
      getRefreshCountType,
      getRefreshCountColor,
      handleCopyToken,
      getExpireTimeStyle,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.login-record-container {
  padding: 20px;
}

.login-record-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #303133;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.login-record-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.card-header .el-icon {
  margin-right: 8px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 图标样式 */
.time-icon {
  color: #409eff;
  font-size: 14px;
}

.ip-icon {
  color: #67c23a;
  font-size: 14px;
}

.refresh-icon {
  color: #e6a23c;
  font-size: 14px;
}

.logout-icon {
  color: #909399;
  font-size: 14px;
}

.expire-icon {
  color: #f56c6c;
  font-size: 14px;
}

.comment-icon {
  color: #909399;
  font-size: 14px;
}

.error-icon {
  color: #f56c6c;
  font-size: 14px;
}

.location-icon {
  color: #409eff;
  font-size: 14px;
}

.browser-icon {
  color: #67c23a;
  font-size: 14px;
}

.os-icon {
  color: #e6a23c;
  font-size: 14px;
}

.device-icon {
  color: #909399;
  font-size: 14px;
}

/* 刷新次数展示样式 */
.refresh-count-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.progress-container {
  width: 100%;
}

.el-progress--line {
  margin-top: 8px;
}

/* 表格行悬停效果增强 */
.el-table__row:hover {
  background-color: #f5f7fa !important;
  transition: background-color 0.2s ease;
}

/* 表格列居中对齐优化 */
.el-table__cell {
  display: flex;
  align-items: center;
}

/* 加载状态增强 */
:deep(.el-table__empty-block) {
  padding: 60px 0;
}

:deep(.el-table__empty-text) {
  font-size: 16px;
  color: #909399;
}

/* 列标题样式优化 */
:deep(.el-table__header) .el-table__cell {
  font-weight: 600;
  color: #303133;
}

/* 用户名列强调效果 */
.el-table__cell:nth-child(1) {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-record-container {
    padding: 10px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input {
    width: 100% !important;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>